<%-- 
    Document   : page
    Created on : 2014/8/21, 上午 09:27:58
    Author     : gjun
--%>

<%@page import="java.util.HashMap"%>
<%@page import="java.util.ArrayList"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String username=request.getParameter("username");
String where=" ";
if(username!=null && !"".equals(username.trim())){
    where="where username like '%"+username+"%'";
}
dao.BaseDAO y=new dao.BaseDAO();
String sql="select count(*) as total from person "+where;
String[] ary={};
ArrayList list=y.query(sql,ary);
String total=(String)((HashMap)list.get(0)).get("total");//取得hashmap的total值
int pagesize=10;//每頁筆數
int pages=Integer.parseInt(total)/pagesize;//總頁數
if(Integer.parseInt(total)%pagesize!=0)
    pages++;
String pageNo=request.getParameter("pageNo");//使用者指定的頁碼
if(pageNo==null)
    pageNo="1";
int index=(Integer.parseInt(pageNo)-1)*pagesize;//資料庫起始的位置

//sql="select * from person limit ?,?";
//ary=new String[]{index+"",pagesize+""};
sql="select * from person "+where+" limit "+index+","+pagesize;
list=y.query(sql,ary);
System.out.println(list);
int lastPage=Integer.parseInt(pageNo)==1?1:Integer.parseInt(pageNo)-1;//上一頁
int nextPage=Integer.parseInt(pageNo)==pages?pages:Integer.parseInt(pageNo)+1;//下一頁
%>
<c:set var="list" value="<%=list%>"/>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Hello World!</h1>
        <script>
            function goPage(pageNo){
                    document.getElementById('pageNo').value=pageNo;
                    document.getElementById('form1').submit();
            }
        </script>
        <form action="page.jsp" id="form1" >  
            <input type="text" name="username" value="${param.username}">
            <input type="hidden" name="pageNo" id="pageNo" value="1" >
            <input type="submit" value="搜尋">
        </form>
        <!--<a href="page.jsp?pageNo=<%=lastPage%>">上一頁</a>-->
        <input type="button" value="上一頁" onclick="goPage('<%=lastPage%>')">
        總共有<%=total%>筆，目前頁碼:<%=pageNo%>,
        每頁<%=pagesize%>筆，共有<%=pages%>頁
        <input type="button" value="下一頁" onclick="goPage('<%=nextPage%>')">
        <!--<a href="page.jsp?pageNo=<%=nextPage%>">下一頁</a>-->
        <br>
        <c:forEach var="x" items="${list}">
            <c:out value="${x.id}"/>,
            <c:out value="${x.username}"/>,
            <c:out value="${x.tel}"/>,
            <c:out value="${x.birthday}"/><br>
        </c:forEach>
        
    </body>
</html>
